var configMgr = {

    init: function () {
        this._initField();
        this._initScope();
        this._initTable();
    },

    _initField: function () {

        this.statusType = {
            0: "开启",
            1: "关闭"
        }
    },

    _initScope: function () {

        var scope = $('body').scope();
        this.scope = scope;

        this.scope.safeApply(function () {
            this.scope.invalid = {field: null, msg: ""};
            this.scope.operator = {};
            this.scope.onAdd = this.onAdd.bind(this);
            this.scope.onEdit = this.onEdit.bind(this);
            this.scope.onSave = this.onSave.bind(this);
            this.scope.onCancel = this.onCancel.bind(this);
            this.scope.onStart = this.onStart.bind(this);
            this.scope.onStop = this.onStop.bind(this);
            this.scope.onSaveStatus = this.onSaveStatus.bind(this);
        }.bind(this));
    },

    _initTable: function () {
        var id = "#client_table";
        $(id).bootstrapTable({
            method: "get",  //使用get请求到服务器获取数据
            url: createUrl("/client_config/list"),
            locale: "zh-CN",
            striped: true,  //表格显示条纹
            pagination: true, //启动分页
            pageSize: 10,  //每页显示的记录数
            pageNumber:1, //当前第几页
            pageList: [10, 25, 50],  //记录数可选列表
            search: false,  //是否启用查询
            showColumns: false,  //显示下拉框勾选要显示的列
            columns:[
                {
                    width:60 //ID
                },
                {
                    width:140 //标题
                },
                {
                    width:200 //内容
                },
                {
                    width:100, //createTime
                    formatter: function (data) {
                        //日期
                        var date = new Date(data);
                        var timeStr = date.format('yyyy-MM-dd');
                        return timeStr;
                    }.bind(this)
                },
                {
                    width:60, //状态
                    formatter: function (data) {
                        var name = "";
                        if (data == 0) {
                            name = "开启";
                        } else {
                            name = "关闭";
                        }
                        return name;
                    }.bind(this)
                },
                {
                    width:100, //编辑
                    formatter: function (value,row,index) {
                        var item = row;
                        var status = item.status;
                        var html = "<a href='javascript:void(0)' ng-click=\"onEdit(" + index + ")\">编辑</a> &nbsp;";
                        if (status == 0) {
                            html += "<a href='javascript:void(0)' ng-click=\"onStop(" + index + ")\">关闭</a>";
                        } else {
                            html += "<a href='javascript:void(0)' ng-click=\"onStart(" + index + ")\">开启</a>";
                        }
                        return html;
                    }.bind(this)
                }
            ],
            sortable:false,
            showRefresh: false,  //显示刷新按钮
            sidePagination: "server", //表示服务端请求
            //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType : "undefined",
            queryParams: function queryParams(params) {   //设置查询参数
                return params;
            }.bind(this),
            onLoadSuccess: function(data){  //加载成功时执行
                this.clientList = data.rows;
                //alert("加载成功");
            }.bind(this),
            onLoadError: function(){  //加载失败时执行
                alert("加载数据失败");
            },
            onPostBody: function() {
                this.scope.compile($(id))(this.scope);
            }.bind(this)
        });
    },

    _refreshTable: function () {
        $("#client_table").bootstrapTable("refresh");
    },

    onAdd: function () {
        this.operateType = "add";
        this._initCurrentData();
        this._initOperatorBase();
        this.scope.operateTitle = "新增配置";
        this.scope.editShow = false;

        $("#editModal").modal("show").css({
            width: 'auto'
        });
    },

    onEdit: function (index) {
        this.operateType = "edit";
        this.currentIndex = index;
        this.scope.operateTitle = "编辑配置";
        this._initCurrentData();
        this._initOperatorBase();
        this.scope.editShow = true;

        $("#editModal").modal("show").css({
            width: 'auto'
        });
    },

    onSave: function () {
        var param = this._getOperateParam();
        if(param.state != 0) {
            return;
        }
        this.scope.error_visible = false;

        $.ajax({
            "url": param.url,
            "type":"post",
            "data":JSON.stringify(param.data),
            "cache": false,
            dataType: 'text',
            "contentType": "application/json; charset=utf-8",
            "success": function(json){
                var ret = parseInt(json);
                if(ret >= 0) {
                    this._refreshTable();
                    $('#editModal').modal('hide');

                    this._clearOperateParam();
                } else {
                    alert("操作失败！");
                }
            }.bind(this),
            "error" : function(msg) {
                alert("操作失败！" + msg);
            }
        });
    },

    onCancel: function () {
        this._clearOperateParam();
    },

    onStart: function (index) {
        this.operateType = "start";
        this.currentIndex = index;
        this.scope.switchTitle = "启动配置";
        this._initCurrentData();

        $("#switchModal").modal("show").css({
            width: 'auto'
        });
    },

    onStop: function (index) {
        this.operateType = "stop";
        this.currentIndex = index;
        this.scope.switchTitle = "关闭配置";
        this._initCurrentData();

        $("#switchModal").modal("show").css({
            width: 'auto'
        });
    },

    onSaveStatus: function () {
        var url = null;
        if (this.operateType == "start"){
            url = createUrl("/client_config/start");
        } else if (this.operateType == "stop"){
            url = createUrl("/client_config/stop");
        }

        $.ajax({
            "url": url,
            "type":"post",
            "data":JSON.stringify(this.scope.currentData),
            "cache": false,
            dataType: 'text',
            "contentType": "application/json; charset=utf-8",
            "success": function(json){
                var ret = parseInt(json);
                if(ret >= 0) {
                    this._refreshTable();
                    $('#switchModal').modal('hide');

                    this._clearOperateParam();
                } else {
                    alert("操作失败！");
                }
            }.bind(this),
            "error" : function(msg) {
                alert("操作失败！" + msg);
            }
        });
    },

    _initCurrentData: function () {
        if (this.operateType == "add") {
            this.scope.currentData = {
                "id":null,
                "name":null,
                "content":null,
                "status":0
            }
        } else if(this.operateType == "edit") {
            this.scope.currentData = this._copyData(this.clientList[this.currentIndex]);
        } else {
            this.scope.currentData = this._copyData(this.clientList[this.currentIndex]);
        }
    },

    _initOperatorBase: function () {
        this.scope.operator.id = this.scope.currentData.id;
        this.scope.operator.name = this.scope.currentData.name;
        this.scope.operator.content = this.scope.currentData.content;
        this.scope.operator.status = this.scope.currentData.status;

        if (this.scope.currentData.status == 0) {
            this.scope.operator.openStatus = true;
        } else {
            this.scope.operator.openStatus = false;
        }
    },

    _copyData: function (data) {
        var ret = {};
        for(var p in data) {
            ret[p] = data[p];
        }
        return ret;
    },

    /**
     * 验证操作信息
     */
    _validateOperateParam: function (data) {
        this.scope.invalid.field = null;
        var cfgs = this._getInValidCfg();
        for (var i = 0; i < cfgs.length; i++) {
            var inValid = false;
            var cfg = cfgs[i];
            if (cfg.fn) {
                inValid = cfg.fn(data);
            } else {
                inValid = isNull(data[cfg.field]);
            }
            if (inValid) {
                this.scope.safeApply(function () {
                    this.scope.invalid.field = cfg.field;
                    this.scope.invalid.msg = cfg.msg;
                }.bind(this));
                return -1;
            }
        }
        return 0;
    },

    /**
     * 获取操作信息
     */
    _getOperateParam : function() {
        var ret = {};
        var status = 0;
        if (this.scope.operator.openStatus == true) {
            status = 0;
        } else {
            status = 1;
        }
        switch (this.operateType) {
            case "add":
                ret.url = createUrl("/client_config/add");
                ret.data = {
                    "id": null,
                    "name": this.scope.operator.name,
                    "content": this.scope.operator.content,
                    "status": status
                };
                break;
            case "edit":
                ret.url = createUrl("/client_config/edit");
                ret.data = {
                    "id": this.scope.currentData.id,
                    "name": this.scope.operator.name,
                    "content": this.scope.operator.content,
                    "status": status
                };
                break;
        }

        //todo: region
        ret.state = this._validateOperateParam(ret.data);
        return ret;
    },

    /**
     * 获取验证信息
     * @returns {*[]}
     */
    _getInValidCfg: function () {
        var info = [
            {
                field: "name", msg: "不能为空！", fn: function (data) {
                var inValid = isNull(data.name);
                return inValid;
            }.bind(this)
            }
        ];
        return info;
    },

    /**
     * 清除操作信息
     */
    _clearOperateParam : function() {
        this.scope.invalid.field = null;
        this.operateType = "";
        this.scope.currentData = {};
    }

};

$(document).ready(function () {
    configMgr.init();
});
